<?php

namespace services\rbac;

use common\models\member\Member;
use Yii;
use api\modules\v1\forms\rbac\DepartmentForm;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\member\Attr;
use common\models\member\AttrLog;
use common\models\rbac\Department;

/**
 * Class DepartmentService
 * @package services\rbac
 */
class DepartmentService extends Service
{
    /**
     * 根据ID获取部门信息
     *
     * @param int $id
     * @return Department|null
     */
    public function findById(int $id = 0): ?Department
    {
        return Department::find()->where(['id' => $id])->one();
    }

    /**
     * 获取部门信息
     *
     * @param array $condition
     * @return Department|null
     */
    public function findInfo(array $condition = []): ?Department
    {
        $query = Department::find();

        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['name']) && $query->andWhere(['name' => $condition['name']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = Department::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

    /**
     * 部门列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function departmentListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = Department::find()->select(['*'])
            ->where(['project_id' => $params['project_id']]);

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['sort' => SORT_ASC, 'status' => SORT_DESC, 'id' => SORT_ASC])
            ->asArray()
            ->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }

    /**
     * 格式化部门列表
     *
     * @param array $data
     * @return array
     */
    public function departmentListPageFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'name' => $row['name'],
                'department_leader' => $row['department_leader'],
                'status' => $row['status'],
                'status_str' => Department::$statuss[$row['status']],
                'total_num' => $row['total_num'],
            ];
        }

        return $list;
    }

    /**
     * 新增部门
     *
     * @param DepartmentForm $model
     * @param array $params
     * @return array|mixed
     */
    public function create(DepartmentForm $model, array $params = [])
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.新增部门
            $department = new Department();
            $department->project_id = $model->project_id;
            $department->name = $model->name;
            $department->department_leader = $model->getDepartmentLeader();
            $department->total_num = $model->getTotalNum();
            $department->status = $model->status;
            $department->save();

            // 2.更新会员属性【设为负责人】
            foreach ($model->getMemberAttrList() as $row) {
                // 2-1.更新会员属性
                $attributes = [
                    'department_id' => $department->id,
                    'is_department_leader' => Attr::IS_DEPARTMENT_LEADER_YES,
                ];
                Attr::updateAll($attributes, [
                    'member_id' => $row['member_id'],
                    'project_id' => $model->project_id,
                ]);

                // 2-2.属性变动日志
                $attrLog = new AttrLog();
                $attrLog->member_id = $row['member_id'];
                $attrLog->content = "设为【{$model->name}】部门负责人";
                $attrLog->log_type = AttrLog::LOG_TYPE_LEADER;
                $attrLog->operate_id = $params['member_id'];
                $attrLog->created_ip = Yii::$app->request->getUserIP();
                $attrLog->save();
            }

            $transaction->commit();

            return ['id' => $department->id];
        } catch (\Exception $e) {
            $transaction->rollBack();

            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑部门
     *
     * @param DepartmentForm $model
     * @param array $params
     * @return array|mixed
     */
    public function edit(DepartmentForm $model, array $params = [])
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            // 1.更新部门
            $attributes = [
                'name' => $model->name,
                'department_leader' => $model->getDepartmentLeader(),
                'total_num' => $model->getTotalNum(),
                'status' => $model->status,
            ];
            Department::updateAll($attributes, ['id' => $model->id]);

            // 2.更新会员属性【取消负责人】
            foreach ($model->getMemberAttrCancelList() as $row) {
                // 2-1.更新会员属性
                $attributes = [
                    'is_department_leader' => Attr::IS_DEPARTMENT_LEADER_NO,
                ];
                Attr::updateAll($attributes, [
                    'member_id' => $row['member_id'],
                    'project_id' => $model->project_id,
                ]);

                // 2-2.属性变动日志
                $attrLog = new AttrLog();
                $attrLog->member_id = $row['member_id'];
                $attrLog->content = "取消【{$model->name}】部门负责人";
                $attrLog->log_type = AttrLog::LOG_TYPE_LEADER;
                $attrLog->operate_id = $params['member_id'];
                $attrLog->created_ip = Yii::$app->request->getUserIP();
                $attrLog->save();
            }

            // 3.更新会员属性【设为负责人】
            foreach ($model->getMemberAttrList() as $row) {
                // 3-1.更新会员属性
                $attributes = [
                    'department_id' => $model->id,
                    'is_department_leader' => Attr::IS_DEPARTMENT_LEADER_YES,
                ];
                Attr::updateAll($attributes, [
                    'member_id' => $row['member_id'],
                    'project_id' => $model->project_id,
                ]);

                // 3-2.属性变动日志
                $attrLog = new AttrLog();
                $attrLog->member_id = $row['member_id'];
                $attrLog->content = "设为【{$model->name}】部门负责人";
                $attrLog->log_type = AttrLog::LOG_TYPE_LEADER;
                $attrLog->operate_id = $params['member_id'];
                $attrLog->created_ip = Yii::$app->request->getUserIP();
                $attrLog->save();
            }

            $transaction->commit();

            return ['id' => $model->id];
        } catch (\Exception $e) {
            $transaction->rollBack();

            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑部门
     *
     * @param DepartmentForm $model
     * @return array|mixed
     */
    public function editStaus(DepartmentForm $model)
    {
        try {
            // 1.更新部门
            $attributes = [
                'status' => $model->status,
            ];
            Department::updateAll($attributes, ['id' => $model->id]);

            return ['id' => $model->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 获取输液室部门人员列表
     * @return array
     */
    public function getInfusionDepartmentUserList(): array
    {
        $ids = Department::find()
            ->select(['id'])
            ->where([
                'project_id' => Yii::$app->params['project_id'],
                'name' => Department::NAME_INFUSION,
                'status' => Department::STATUS_ENABLE,
            ])
            ->column();
        if (empty($ids)) {
            return [];
        }

        $data = Member::find()->alias('m')
            ->select([
                'm.id', 'm.realname',
                'ma.department_id'
            ])
            ->innerJoin(Attr::tableName().' ma', 'ma.member_id = m.id')
            ->where([
                'm.status' => Member::STATUS_ENABLE,
                'ma.project_id' => Yii::$app->params['project_id'],
                'ma.department_id' => $ids,
            ])
            ->asArray()
            ->all();
        return $data;
    }
}
